import Vue from 'vue'
import axios from 'axios'
import VueAxios from 'vue-axios'

Vue.use(VueAxios, axios)

import {getToken,saveToken} from './token.js'
import { Toast } from 'vant'
import router from '../router/index.js'

const instance = axios.create({
    baseURL: 'http://toutiao.itheima.net',
    timeout: 20000
  })

  instance.interceptors.request.use(
    function (config) {
      // 在发送请求之前做些什么
      if(getToken()){
        config.headers={
          Authorization:`Bearer ${getToken().token}`
        }
      }
      return config
    },
    function (error) {
      // 对请求错误做些什么
      return Promise.reject(error)
    }
  )

  // 添加响应拦截器
  instance.interceptors.response.use(
    function (response) {
      // 对响应数据做点什么
      return response
    },
    async function (error) {
      // 对响应错误做点什么
      console.dir(error);
      if(error.response.status==401){
        if(getToken()){
          try {
            let res=await axios({
              url:'http://toutiao.itheima.net/v1_0/authorizations',
              method:'put',
              headers:{
                Authorization:`Bearer ${getToken().refresh_token}`
              }
            })
            console.log(res);
            let obj=getToken();
            obj.token=res.data.data.token;
            saveToken(obj)
            return instance(error.config)
          } catch (error) {
            Toast.fail('请先登录');
            router.push({path:'/login'});
          }
        }else{
          Toast.fail('请先登录')
          router.push({path:'/login'})
        }
      }else{

      }
      return Promise.reject(error)
    }
  )




export default instance
